package com.zadtek.jpsqishi.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.zadtek.jpsqishi.R;
import com.zadtek.jpsqishi.activity.common.Common;
import com.zadtek.jpsqishi.activity.common.Const;
import com.zadtek.jpsqishi.activity.data.QiangDanData;
import com.zadtek.jpsqishi.frame.JsonProcessHelper;

/**
 * 我的定位
 *
 * @author Administrator
 */
public class MyLoaction extends Activity implements AMapLocationListener {
    private ImageView backid;
    private TextView topview;
    private RelativeLayout locations;
    private TextView location_time, location_address, start;
    TextView myLocationText;

    private Address address;
    SimpleDateFormat formatter;
    Date curDate;

    OrderAsyncTask mOrderAsyn;
    private QiangDanData qiangdan;
    public static Handler mHandler;
    private SharedPreferences sp; // 用户信息缓存
    String Uid = "";

    private AMap aMap;
    // 声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;
    private LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylocation);

        backid = (ImageView) findViewById(R.id.backid);
        topview = (TextView) findViewById(R.id.topview);
        topview.setText("定位");

        myLocationText = (TextView) findViewById(R.id.location_address);
        locations = (RelativeLayout) findViewById(R.id.location);
        start = (TextView) findViewById(R.id.start);
        location_time = (TextView) findViewById(R.id.location_time);
        location_address = (TextView) findViewById(R.id.location_address);

        GetLocation();

        mlocationClient = new AMapLocationClient(this);
        // 初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        // 设置定位监听
        mlocationClient.setLocationListener(this);
        // 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
        // 设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        // 设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        // 启动定位
        mlocationClient.startLocation();

        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        Uid = sp.getString("uid", "");

        locations.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (Common.isNetworkConnected(MyLoaction.this)) {

                    if (mlocationClient != null && mlocationClient.isStarted()) {

                        Common.DisplayToast(MyLoaction.this, "定位成功", 1);
                    } else {
                        System.out.println("locClient is null or not started");
                    }
                } else {
                    Common.DisplayToast(MyLoaction.this, "通信失败,请检查网络!", 1);
                }
            }
        });

        backid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                MyLoaction.this.finish();

            }
        });

        mHandler = new Handler() {
            @SuppressWarnings("unchecked")
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS://
                        qiangdan = new QiangDanData();
                        qiangdan = (QiangDanData) msg.obj;
                        if (qiangdan.getStatus().equals("0")) {

                            Common.DisplayToast(MyLoaction.this,
                                    qiangdan.getMessage(), 1);
                        }
                        break;
                    case Const.STATE_START_ERROR://
                        Common.DisplayToast(MyLoaction.this, "获取数据失败", 1);
                        break;
                }
            }
        };
    }

    class OrderAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("qiangdan")) {// 更新坐标
                if (Const.latitude.length() > 0 && Const.lontitude.length() > 0
                        && !Const.latitude.equals("0")
                        && !Const.lontitude.equals("0")
                        && !Const.lontitude.contains("E")
                        && !Const.latitude.contains("E")) {
                    qiangdan = new QiangDanData();
                    qiangdan = JsonProcessHelper.jsonProcess_setEmpLocation(
                            "set_emp_location", Uid, Const.latitude,
                            Const.lontitude);// emp_id(快递ID)，lat(纬度)，lng(经度)
                    if (qiangdan != null) {
                        res = "state_success";
                    } else {
                        res = "mi_error";
                    }
                }
            }
            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("state_success")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = qiangdan;
                mHandler.sendMessage(msg);
            } else if (result.equals("mi_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            }
        }
    }

    private void GetLocation() {
        // 获取LocationManager服务
        locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 如果未设置位置源，打开GPS设置界面
        if (locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            start.setText("已开启");
            return;
        }
        start.setText("未开启");

    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                // 定位成功回调信息，设置相关消息
                // amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();// 获取纬度
                amapLocation.getLongitude();// 获取经度
                amapLocation.getAccuracy();// 获取精度信息
                if (amapLocation.getLatitude() > 0 && amapLocation.getLongitude() > 0) {

                    SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
                    String str = sdf.format(amapLocation.getTime());

                    location_time.setText(str + "   lbs   精确到10米");
                    myLocationText.setText(amapLocation.getAddress());
                    LatLng lng1 = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                    LatLng lng2 = new LatLng(Double.parseDouble(Const.latitude), Double.parseDouble(Const.lontitude));
                    float distance = AMapUtils.calculateLineDistance(lng1, lng2);
                    if (!Const.latitude.equals(amapLocation
                            .getLatitude() + "") && !Const.lontitude.equals(amapLocation
                            .getLongitude() + "")) {
                        Const.latitude = amapLocation.getLatitude() + "";
                        Const.lontitude = amapLocation.getLongitude() + "";
                        if (distance > 100) {
                            new OrderAsyncTask().execute("qiangdan");
                        }
                    }
                } else {
                    Common.DisplayToast(MyLoaction.this, "请再次定位", 1);
                }
            } else {
                Toast.makeText(MyLoaction.this, "定位失败,请检查网络!" + amapLocation.getErrorCode(),
                        Toast.LENGTH_SHORT).show();

            }
        }
    }

    @Override
    protected void onDestroy() {
        mlocationClient.stopLocation();
        super.onDestroy();
    }

}
